package work.huangxin.share.controller.talk;

import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import work.huangxin.share.domain.sechand.SechandGoods;
import work.huangxin.share.service.impl.MinioSysFileServiceImpl;
import work.huangxin.share.util.status.ResponseData;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: 张锦标
 * @date: 2023/3/26 8:27
 * FileUpDownController类
 */
@RequestMapping("/wx/file")
@RestController
public class FileUpDownController {
    //
    //@Autowired
    //private ISysFileService sysFileService;
    @Autowired
    private MinioSysFileServiceImpl minioSysFileService;
    @Autowired
    @Qualifier("fileThreadPool")
    private ThreadPoolExecutor fileThreadPool;

    private static final Logger log = LoggerFactory.getLogger(FileUpDownController.class);
    @ApiOperation(value = "多附件上传-纯附件上传", notes = "多附件上传")
    @ResponseBody
    @PostMapping("/uploadFiles")
    public ResponseData<SechandGoods> handleFileUpload(
            @RequestParam("files") MultipartFile[] files) {
        SechandGoods sechandGoods = new SechandGoods();
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(files.length);
        for (int i = 0; i < files.length; i++) {
            try {
                MultipartFile file = files[i];
                //TODO 使用CountDownLaunch或者ComplatableFuture或者Semaphore
                //来完成多线程的文件上传
                fileThreadPool.submit(() -> {
                    try {
                        String url = minioSysFileService.uploadFile(file);
                        list.add(url);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        //表示一个文件已经被完成
                        countDownLatch.countDown();
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        try {
            //阻塞直到所有的文件完成复制
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //统计每个文件的url
        String photoUrls = String.join(",", list);
        sechandGoods.setGoodsPhotos(photoUrls);
        return ResponseData.success(sechandGoods);
    }


    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam String name, HttpServletResponse response) {
        //FileInputStream fis = null;
        //ServletOutputStream os = null;
        try (FileInputStream fis = new FileInputStream(new File(name));
             ServletOutputStream os = response.getOutputStream()) {
            //输入流,通过输入流读取文件内容
            //fis = new FileInputStream(new File( name));
            //输出流,通过输出流将文件写回浏览器,在浏览器展示图片
            //os = response.getOutputStream();
            //设置响应的数据的格式
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] buffre = new byte[1024 * 10];
            while ((len = fis.read(buffre)) != -1) {
                os.write(buffre, 0, len);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
